import React from 'react';
import { Layout } from 'antd';
import { Route, HashRouter, Switch, Redirect } from 'react-router-dom';
import routers from './routers';
import LoadPage from './loadable';

import Head from '@src/common/components/header';
import Foot from '@src/common/components/footer';
import Sider from '@src/common/components/sider';
import Breadcrumb from '@src/common/components/bread';

import { page, content } from './router.less';

import { useAppDispatch } from '@store/hooks';
import { setMenu } from '@store/reducers/leftSiderSlice';

const { Content } = Layout;

// 加载组件
function loadComponent(item: RouterItem) {
    if ('redirect' === item.src && item.redirect) {
        return (
            <Route exact key={item.path} path={item.path} render={() => <Redirect to={item.redirect || ''} />}></Route>
        );
    }
    return (
        <Route
            exact
            key={item.path}
            path={item.path}
            component={LoadPage(() => import(`@src/view${item.src}`), item)}
        ></Route>
    );
}

// 循环生成路由列表
function loadRouter(arr: Array<RouterItem>, routerArr: Array<JSX.Element>) {
    arr.forEach((item: RouterItem) => {
        let route = loadComponent(item);
        routerArr.push(route);
        item.children && loadRouter(item.children, routerArr);
    });
    return routers;
}

function AppRouter() {
    const dispatch = useAppDispatch();
    dispatch(setMenu(routers));

    const routerArr: JSX.Element[] = [];
    loadRouter(routers, routerArr);
    return (
        <HashRouter>
            <Layout className={page}>
                <Head></Head>
                <Layout>
                    <Sider></Sider>
                    <Layout style={{ padding: '0', overflow: 'hidden', backgroundColor: '#fff' }}>
                        <Breadcrumb></Breadcrumb>
                        <Content
                            className={content}
                            style={{
                                padding: '0',
                                margin: 0,
                                minHeight: 280,
                                overflow: 'auto',
                            }}
                        >
                            <Switch>
                                {/* <React.Suspense fallback={<div>fallback loading</div>}></React.Suspense> */}
                                {/* Switch只显示一个组件。加exact表示精确匹配/。如果不加exact，/xxx也会匹配/ */}
                                {/* exact */}
                                <Route exact path="/" render={() => <Redirect to="/index" />} />
                                {routerArr}
                                <Route path="*" render={() => <Redirect to="/notFound" />} />
                            </Switch>
                        </Content>
                    </Layout>
                </Layout>
                <Foot></Foot>
            </Layout>
        </HashRouter>
    );
}

export default AppRouter;
